package org.grayrabbit.cms.plugin.descriptors;

import org.dom4j.Element;
import org.grayrabbit.cms.plugin.ModuleDescriptorFactory;
import org.grayrabbit.cms.plugin.Plugin;
import org.grayrabbit.cms.plugin.PluginParseException;


public class UnrecognisedModuleDescriptorFactory {

	public static UnrecognisedModuleDescriptor createUnrecognisedModuleDescriptor(Plugin plugin, Element element, Throwable e,
			ModuleDescriptorFactory moduleDescriptorFactory) throws PluginParseException {
		UnrecognisedModuleDescriptor descriptor = new UnrecognisedModuleDescriptor();
		descriptor.init(plugin, element);
		String name = element.getName();
		Class<?> moduleClass = moduleDescriptorFactory.getModuleDescriptorClass(name);
		String moduleClassName;
		if (moduleClass == null)
			moduleClassName = descriptor.getKey();
		else {
			moduleClassName = moduleClass.getName();
		}
		String errorMsg = constructErrorMessage(plugin, name, moduleClassName,e);

		descriptor.setErrorText(errorMsg);

		return descriptor;
	}

	 private static String constructErrorMessage(Plugin plugin, String moduleName, String moduleClass, Throwable e)
	  {
	    String errorMsg;
	    if ((e.getMessage() == null) || ("".equals(e.getMessage())))
	    {
	      if ((e instanceof PluginParseException)) {
	        errorMsg = "There was a problem loading the descriptor for module '" + moduleName + "' in plugin '" + (plugin == null ? "null" : plugin.getName()) + "'.\n ";
	      }
	      else
	      {
	        if ((e instanceof InstantiationException)) {
	          errorMsg = "Could not instantiate module descriptor: " + moduleClass + ".<br/>";
	        }
	        else
	        {
	          if ((e instanceof IllegalAccessException)) {
	            errorMsg = "Exception instantiating module descriptor: " + moduleClass + ".<br/>";
	          }
	          else
	          {
	            if ((e instanceof ClassNotFoundException)) {
	              errorMsg = "Could not find module descriptor class: " + moduleClass + ".<br/>";
	            }
	            else
	            {
	              if ((e instanceof NoClassDefFoundError))
	                errorMsg = "A required class was missing: " + moduleClass + ". Please check that you have all of the required dependencies.<br/>";
	              else
	                errorMsg = "There was a problem loading the module descriptor: " + moduleClass + ".<br/>"; 
	            }
	          }
	        }
	      }
	    } else {
	      errorMsg = e.getMessage();
	    }
	    return errorMsg;
	  }

}
